package com.qdrtme.landemo.common;

import android.content.Context;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Created by taylor on 9/6/17.
 */

public class Utils {

    public static String getFromAssets(Context c, String fileName) {
        String result = "";
        try {
            InputStreamReader inputReader = new InputStreamReader(c.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";

            while ((line = bufReader.readLine()) != null)
                result += line;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param setCollect 接口参数列表
     *                   当前项目中所有的输入参数按照URL键值对格式拼接，
     *                   并按照字段名的ASCII码从小到大排序进行排序
     * @class description 密钥生成方法
     * @author zhao xiaotong
     */
    public static String getMi(long timeStamp, Set<Map.Entry<String, Object>> setCollect) {
        String mm = "";

        // 1. 按key排序
        List<Map<String, String>> paramList = new ArrayList<>();
        Iterator iter = setCollect.iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
            HashMap<String, String> tempMap = new HashMap<String, String>();
            tempMap.put(key, val);
            paramList.add(tempMap);
        }

        Collections.sort(paramList, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                //o1，o2是list中的Map，可以在其内取得值，按其排序，此例为升序，s1和s2是排序字段值
                HashMap<String, String> m1 = (HashMap<String, String>) o1;
                HashMap<String, String> m2 = (HashMap<String, String>) o2;
                Iterator i1 = m1.entrySet().iterator();
                Iterator i2 = m2.entrySet().iterator();

                Map.Entry e1, e2;
                String k1 = "", k2 = "";
                if (i1.hasNext()) {
                    e1 = (Map.Entry) i1.next();
                    k1 = (String) e1.getKey();
                }
                if (i2.hasNext()) {
                    e2 = (Map.Entry) i2.next();
                    k2 = (String) e2.getKey();
                }

                if (k1.compareToIgnoreCase(k2) > 0) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });

        // 2. 拼接string1
        for (int i = 0; i < paramList.size(); i++) {
            HashMap<String, String> hm1 = (HashMap<String, String>) paramList.get(i);
            Iterator iterator = hm1.entrySet().iterator();
            if (iterator.hasNext()) {
                Map.Entry e1 = (Map.Entry) iterator.next();
                String key = (String) e1.getKey();
                String value = (String) e1.getValue();
                mm += key + "" + value;

//                if (i == paramList.size() - 1) {
//                    mm += key + "=" + value;
//                } else {
//                    mm += key + "=" + value + "&";
//                }
            }
        }

        // 3.
        mm = String.valueOf(timeStamp) + mm + "8w7jv4qb7eb5y";

        System.out.println("## before md5- " + mm);

        // 4. MD5运算转16进制数，并转为大写
        try {
            mm = getMD5(mm); // 保持原样
//            mm = getMD5(mm).toUpperCase();
            System.out.println("## after md5- " + mm);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mm;
    }


    /**
     * MD5加密
     *
     * @param str 需要加密的字符串
     * @return 加密后的字符串
     */
    // 全局数组
    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String getMD5(String strObj) throws UnsupportedEncodingException {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes("utf-8")));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

}
